package uk.gov.swmprobation.cplite;

import java.io.File;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends MyActivity {

	    static TabAdapter tabAdapter;
	    ViewPager viewPager;
	    LocationServices ls = new LocationServices(this);
	    ActionBar actionBar;
	    static List<Integer> projectTypes;
		private BroadcastReceiver backgroundUpdate;
		Intent MQTTIntent;
		private static final int SELECT_IMAGE = 0;
		private Uri fileUri;
		private static String filePath;
		private static MenuItem menuCameraIcon;
		public static Boolean enabledCamera;

	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);

	        enabledCamera = LocationServices.locationAvailable();
	        
	        //If only drafts unsubscribe all
	        if(DatabaseHandler.getProjectsCount()==DatabaseHandler.getProjectsCountType(Project.TYPE_DRAFT)){
	        	Intent unsubscribeIntent = new Intent("uk.gov.swmprobation.cpvisibility.UNSUBSCRIBETOPIC");
				unsubscribeIntent.putExtra("Topic", "projects/#");
				sendOrderedBroadcast(unsubscribeIntent, null);
	        }
	        
	        
	        // Create the adapter that will return a fragment for each of the three primary sections
	        // of the app.
	        tabAdapter = new TabAdapter(getSupportFragmentManager());
	        
	        // Set up the action bar.
	        actionBar = getSupportActionBar();

	        // Specify that the Home/Up button should not be enabled, since there is no hierarchical
	        // parent.
	        actionBar.setHomeButtonEnabled(false);
	        actionBar.setDisplayHomeAsUpEnabled(false);

	        // Specify that we will be displaying tabs in the action bar.
	        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

	        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
	        // user swipes between sections.
	        viewPager = (ViewPager) findViewById(R.id.tabs);
	        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
	            @Override
	            public void onPageSelected(int position) {
	                // When swiping between different app sections, select the corresponding tab.
	                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
	                // Tab.
	            	if(actionBar.getTabCount()>0){
	            		actionBar.setSelectedNavigationItem(position);
	            	}
	            }
	        });

	        backgroundUpdate = new BroadcastReceiver(){

				@Override
				public void onReceive(Context context, Intent intent) {
					setViews();				
					abortBroadcast();
				}
	        	
	        }; 
	        
	        MQTTIntent = new Intent(this,MQTTConnection.class);
			this.startService(MQTTIntent);
			
	    }

	    public void onPause(){
	    	super.onPause();
	    	unregisterReceiver(backgroundUpdate);
	    }
	    
	    public void onDestroy(){
	    	super.onDestroy();
	    	LocationServices.stopListener();
	    	if (!sharedPref.getBoolean("enable_mqtt", true)){
	    		this.stopService(MQTTIntent);
	    	}
	    }
	    
	    @Override
	    public void onResume(){
	    	super.onResume();
	    	setViews();
	    	IntentFilter intentFilter = new IntentFilter();
	        intentFilter.addAction("uk.gov.swmprobation.cpvisibility.event.updatemain");
	        intentFilter.setPriority(1);
	        registerReceiver(backgroundUpdate, intentFilter);
	    	if (!LocationServices.locationAvailable()){
	    		ls.GetLastLocation();
	        	ls.GetALocation();
	        }
	    	enabledCamera = LocationServices.locationAvailable();
	    	if (menuCameraIcon != null){
	    		enableCamera(LocationServices.locationAvailable());
	    	}
	    }

	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu items for use in the action bar
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.application_menu, menu);
	        menuCameraIcon = menu.findItem(R.id.action_camera);
	        enableCamera(LocationServices.locationAvailable());
	        return super.onCreateOptionsMenu(menu);
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle item selection
	        switch (item.getItemId()) {
				case R.id.action_camera:
					return callCamera();
				default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
	    
	    public static void enableCamera(Boolean enable){
	    	enabledCamera = enable;
	    	if(enable){
	    		menuCameraIcon.getIcon().setAlpha(255);
	    	} else {
	    		menuCameraIcon.getIcon().setAlpha(50);
	    	}
	    }
	    
	    public void TakePhotoButton(View v){
	    	callCamera();    	
	    }
	    
	        public boolean callCamera(){
	        	if(Helper.isAirplaneModeOn(this)){
	        		Toast.makeText(this, "Please turn of Airplane mode to continue.", Toast.LENGTH_SHORT).show();
	    	    	return true;
	        	}
	    		if(!LocationServices.locationAvailable()){
	    	    	Toast.makeText(this, "Looking for your location, please try again later.", Toast.LENGTH_SHORT).show();
	    	    	return true;
	    	    }
	    	    
	    	    if(System.currentTimeMillis()-LocationServices.getLocationTime()>LocationServices.FEW_MINUTES){
	    	    	Toast.makeText(this, "Location information may be out of date.", Toast.LENGTH_SHORT).show();
	    	    }

	    		String state = Environment.getExternalStorageState();
	            if (Environment.MEDIA_MOUNTED.equals(state)) {
	            	Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	        		fileUri = getOutputMediaFileUri();
	        		if (fileUri!=null){
	        			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
	        			startActivityForResult(takePictureIntent, SELECT_IMAGE);
	        		} else {
	        			Toast.makeText(this, "Can't save to SD Card.", Toast.LENGTH_SHORT).show();
	        		}
	            } else {
	            	Toast.makeText(this, "Can't access SD Card.", Toast.LENGTH_SHORT).show();
	            }
	            return true;
	    	}    
	        
	    private void setViews(){
	    	
	    	actionBar.removeAllTabs();
	    	projectTypes = DatabaseHandler.getProjectTypes();
	    	tabAdapter.notifyDataSetChanged();
	    	viewPager.setAdapter(tabAdapter);
	        for (int i = 0; i < tabAdapter.getCount(); i++) {
	            actionBar.addTab(
	                    actionBar.newTab()
	                            .setText(tabAdapter.getPageTitle(i))
	                            .setTabListener(this));
	        }
	        
	        
	    }

	    public static class TabAdapter extends FragmentPagerAdapter {
	    	
	        public TabAdapter(FragmentManager fm) {
	            super(fm);
	        }

	        @Override
	        public Fragment getItem(int position) {
		        Fragment fragment = new TabFragment();
		        Bundle args = new Bundle();
		        args.putInt(TabFragment.PROJECT_TYPE, position+1);
		        fragment.setArguments(args);
		        return fragment;
	        }

	        @Override
	        public int getCount() {
	            return Project.TYPE_NAMES.length-3;
	        }

	        @Override
	        public CharSequence getPageTitle(int position) {
	            return Project.TYPE_NAMES[position+1];
	        }
	    }

	    
	    public static class TabFragment extends ListFragment {

	        public static final String PROJECT_TYPE = "project_type";
	    	private List<Project> projects;
	    	Context context;

	        @Override
	        public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                Bundle savedInstanceState) {
	            View rootView = inflater.inflate(R.layout.fragment_main_activity, container, false);
	            Bundle args = getArguments();
	            context = getActivity();
	            setListAdapter(new ProjectListAdapter(args.getInt(TabFragment.PROJECT_TYPE)));
	            
	            ImageButton emptybutton = (ImageButton) rootView.findViewById(android.R.id.empty);
	            if (enabledCamera){
	            	emptybutton.setImageResource(R.drawable.camerabutton);
	            } else {
	            	emptybutton.setImageResource(R.drawable.camera_image_disabled);
	            }
				//emptybutton.setEnabled(enabledCamera);
	            
	            return rootView;
	        }
	        
	        @Override 
	        public void onListItemClick(ListView parent, View v, int position, long id){
	        	if(Helper.isNetworkAvailable(context)){
		        	Project projectToOpen = projects.get(position);
		        	Intent openProjectView;
		        	if (projectToOpen.getProjectType()==Project.TYPE_DRAFT) {
		        		openProjectView = new Intent(context, CreateProject.class);
		        		int idToOpen = projectToOpen.getId();
		        		openProjectView.putExtra("id", idToOpen);
		        	} else {
		        		openProjectView = new Intent(context, ReviewProjects.class);
		        		openProjectView.putExtra("position", position);
		        		openProjectView.putExtra("updated", projectToOpen.getUpdated());
		        	}
		      	    startActivity(openProjectView);
	        	} else {
	        		Toast.makeText(context, "Can't connect to Internet, please try again later.", Toast.LENGTH_LONG).show();
	        	}
	        }
	        
	        private class ProjectListAdapter extends BaseAdapter{
	        	
	        	ProjectListAdapter(int type) {
	        		projects = DatabaseHandler.getTypeProjects(type);
	        	}
	        	
	    			@Override
	    			public int getCount() {
	    				return projects.size();
	    			}

	    			@Override
	    			public Object getItem(int pos) {
	    				return projects.get(pos);
	    			}

	    			@Override
	    			public long getItemId(int pos) {
	    				return pos;
	    			}

	    			@Override
	    			public View getView(int pos, View view, ViewGroup viewGroup) {
	    				view = View.inflate(context, R.layout.projectlist_item, null);
	    				
	    				if(pos % 2 == 1){
	    					view.setBackgroundResource(R.drawable.linkbackgroundodd);
	    				} else {
	    					view.setBackgroundResource(R.drawable.linkbackgroundeven);
	    				}
	    				
	    				Project project = (Project) getItem(pos);
	    				
	    				TextView text = (TextView) view.findViewById(R.id.local_id);
	    	            text.setText(String.valueOf(project.getId()));
	    	            String describeProject;
	    				if (!project.getProjectStatus().equals("Draft")){
	    					describeProject=project.getProjectId() + " - " + Helper.shortName(project.getProjectName());
	    				} else {
	    					describeProject=project.getProjectName();
	    				}
	    	            
	    	            
	    				text = (TextView) view.findViewById(R.id.project_name);
	    	            text.setText(describeProject);

	    	            ImageView  image = (ImageView) view.findViewById(R.id.project_status);
	    	             if (project.getProjectStatus().equals("Waiting")) {
	    	            	image.setImageResource(android.R.drawable.ic_dialog_email);
	    	            	image.setVisibility(View.VISIBLE);
	    	             }
	    	            
	    	            ImageButton button = (ImageButton) view.findViewById(R.id.delete_button);
	    				button.setFocusable(false);
	    		
	    	            return view;
	    			}};
	    			
	    }

		@Override
		public void onTabReselected(Tab arg0,
				android.support.v4.app.FragmentTransaction arg1) {
		}

		@Override
		public void onTabSelected(Tab tab,
				android.support.v4.app.FragmentTransaction arg1) {
			viewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(Tab arg0,
				android.support.v4.app.FragmentTransaction arg1) {
		}
		
			    
	    public void deleteProject(View v) 
	    {
	        //get the row the clicked button is in
	        RelativeLayout parentRow = (RelativeLayout)v.getParent();
	        
	        TextView idText = (TextView) parentRow.getChildAt(0);
	        
	        final int localId = Integer.parseInt((String) idText.getText());
	        
	        final Project projectToDelete = DatabaseHandler.getProject(localId);
	        
	        final String projectName = projectToDelete.getProjectName();

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure you want to delete "+projectName+"?");
		    builder.setTitle("Delete project?");
			builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	   	DatabaseHandler.deleteProject(localId);
			        	   	Intent unsubscribeIntent = new Intent("uk.gov.swmprobation.cpvisibility.UNSUBSCRIBETOPIC");
   			       			unsubscribeIntent.putExtra("Topic", "projects/"+projectToDelete.getProjectId());
   			       			sendOrderedBroadcast(unsubscribeIntent, null);
   			       			setViews();
			           }
			       });
			builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			           }
			       });

			AlertDialog dialog = builder.create();
			dialog.show();
	    }

	    /** Create a file Uri for saving an image */
	    private static Uri getOutputMediaFileUri(){
	          return Uri.fromFile(getOutputMediaFile());
	    }
	    
	    /** Create a File for saving an image or video */
	    @SuppressLint("SimpleDateFormat")
		private static File getOutputMediaFile(){
	    	File mediaFile;
	        //Check SDCard is mounted
	    	String state = Environment.getExternalStorageState();

	    	if (state.equals(Environment.MEDIA_MOUNTED)) {
		        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
		                  Environment.DIRECTORY_PICTURES), "SWM");
				        
		        // Create the storage directory if it does not exist
		        if (! mediaStorageDir.exists()){
		            if (! mediaStorageDir.mkdirs()){
		                return null;
		            }
		        }
		
		        // Create a media file name
		        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
	    	} else {
	    		Toast.makeText(MyApplication.getContext(), "Can't access your SD card", Toast.LENGTH_LONG).show();
	    		return null;
	    	}
	    	filePath = mediaFile.getPath();
	        return mediaFile;
	    }
		
	    @Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
		  super.onActivityResult(requestCode, resultCode, data);
		  if (requestCode == SELECT_IMAGE)
		    if (resultCode == Activity.RESULT_OK) {

		    //Get GPS co-ordinates
		      double lat = LocationServices.getLocationLat();
			  double lng = LocationServices.getLocationLng();
		      Project newproject = new Project(filePath, lat, lng);
		      // Store project
		      newproject.save();
		      
		      //Test internet access
		      if (Helper.isNetworkAvailable(this)){
		    	//If pass open next activity
			      Intent createProject = new Intent(this, CreateProject.class);
			      createProject.putExtra("id", newproject.getId());
			      startActivity(createProject);
		      } else {
		    	  Toast.makeText(this, "Can't access internet - Project saved to drafts.", Toast.LENGTH_LONG).show();
		      }
		      
		      
		      
		    } 
		}
	    
	}

